package com.fxc;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;

import com.fxc.TankFrame;
import com.fxc.tank.abstractfactory.BaseBullet;

public class Bullet extends BaseBullet{
	
	private static final int SPEED = Integer.parseInt((String)PropertyManager.get("bulletSpeed"));
	
	// 子弹的大小
	public static final int WIDTH  = ResourceManager.bullet.getWidth();
	public static final int HEIGHT = ResourceManager.bullet.getHeight();
	
	Rectangle rect = new Rectangle();
	
	private boolean liveing = true;
	
	private Group group = Group.BAD;
	
	private int x, y;
	
	public Group getGroup() {
		return group;
	}

	public void setGroup(Group group) {
		this.group = group;
	}

	private Dir dir;
	
	TankFrame tf = null;

	public Bullet(int x, int y, Dir dir, TankFrame tf,Group group) {
		super();
		this.x = x;
		this.y = y;
		this.dir = dir;
		this.tf = tf;
		this.group = group;
		
		rect.x = this.x;
		rect.y = this.y;
		rect.width = WIDTH;
		rect.height = HEIGHT;
		
		tf.bullets.add(this);
	}
	
	public void paint(Graphics g) {
		if (!isLive()) {
			tf.bullets.remove(this);
		} 
		// 渲染图形
//		Color color = g.getColor();
//		
//		g.setColor(color.red);
//		
//		g.fillOval(x, y,WIDTH, HEIGHT);
//		
//		g.setColor(color);
		
		// 渲染图片
		g.drawImage(ResourceManager.bullet, x , y, null);

		move();
	}

	// 移动
	private void move() {
		
		switch (dir) {
		case LEFT:
			x -= SPEED;
			break;
		case UP:
			y -= SPEED;
			break;
		case RIGHT:
			x += SPEED;
			break;
		case  DOWN:
			y += SPEED;
			break;

		default:
			break;
		}
		
		// update rect
		rect.x = this.x;
		rect.y = this.y;
		
		
		// 子弹的存活
		if(x < 0 || y< 0 || x > TankFrame.GMAE_WIDTH || y > TankFrame.GAME_HEIGHT ) {
			setLive(false);
		}
	}

	public boolean isLive() {
		return liveing;
	}

	public void setLive(boolean live) {
		this.liveing = live;
	}

	// 坦克碰撞
	public void collideWIth(Tank tank) {
		if (this.group == tank.getFrGroup()) {
			return;
		}
		
		// Rectangle rect1 = new Rectangle(this.x,this.y, WIDTH, HEIGHT);
		
		// Rectangle rect2 = new Rectangle(tank.getX(), tank.getY(), tank.WIDTH, tank.HEIGHT);
		
		if (rect.intersects(tank.rect)) {
			
			tank.die();
			
			this.die();
		
			int eX = tank.x  + Tank.WIDTH/2 - Explods.WIDTH/2;
			
			int eY = tank.y  + Tank.HEIGHT /2- Explods.HEIGHT/2;
			
			tf.explods.add(tf.gf.BaseExplode(eX, eY, tf));	
		}
	}

	private void die() {
		this.liveing = false;
	}
	
}
